<?php

namespace app\admin\controller;

use think\App;
class Export extends Base{
    protected $isSink = true;
    public function __construct(App $app = null){
        parent::__construct($app);
        ini_set('memory_limit', '-1');
    }

    /**
     * 导出数据
     * @param string $mod       导出模型
     * @param string $where     导出条件
     * @param string $field     导出字段
     * @param string $order     排序
     * @return \think\Response
     * @throws \ReflectionException
     */
    public function export($mod='',$where='', $field ='*',$order=''){
        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        $header = [];
        $title = '';
        $prefix = config('database.prefix');
        $name = strtolower($prefix.$mod);
        $name = ucfirst($name);
        $class = new \ReflectionClass("\\app\\admin\\model\\$name");
        $instance  = $class->newInstanceArgs();
        $this->model = $instance;
        $where = $where?$this->_where($where):'';
        $counts = method_exists($instance,'counts');
        if ($counts){
            $result = $instance->counts($where);
        }else{
            $result = $instance->where($where)->count();
        }
        if(request()->isPost()){
            if(!$result){
                return $this->__e('没有符合条件的数据');
            }else{
                $params['mod'] = $mod;
                if($where){
                    $params['where1'] = $where;
                }
                if($field!='*'){
                    $params['field'] = $field;
                }
                $query = http_build_query($params);
                $host = request()->host();
                $url = "http://{$host}/admin/export?{$query}";
                return $this->__s('查询成功,本次可导出'.$result.'条数据',['url'=>$url]);
            }
        }
        $tableName = $instance->getTable();
        $fields = '';
        $_field  = [];
        $sql = "SELECT column_name as column_name,column_comment as column_comment,data_type as data_type  FROM information_schema.COLUMNS WHERE TABLE_NAME = '{$tableName}'";
        $sql1 = "SELECT table_name,table_comment FROM information_schema.TABLES WHERE TABLE_NAME='{$tableName}'";
        $_fields = $instance->query($sql);
        $_table = $instance->query($sql1);
        $header['sort']='排序';
        if(strpos($field,'*')===false){
            $field = explode(',',$field);
            foreach ($_fields as $v){
                if(in_array($v['column_name'],$field)){
                    array_push($_field,$v['column_name']);
                    $fields .= ','.$v['column_name'];
                    if(strpos($v['column_comment'],':')===false){
                        $column_comment = explode(' ',$v['column_comment']);
                        $comment = $column_comment[0];
                    }else{
                        $column_comment = explode(':',$v['column_comment']);
                        $comment = $column_comment[0];
                    }
                    $comment = $comment?$comment:$v['column_name'];
                    $header[$v['column_name']] = $comment;
//                    array_push($header,$_header);
                }
            }
        }else{
            foreach ($_fields as $k => $v){
                if(strpos($v['column_comment'],':')===false){
                    $column_comment = explode(' ',$v['column_comment']);
                    $comment = $column_comment[0];
                }else{
                    $column_comment = explode(':',$v['column_comment']);
                    $comment = $column_comment[0];
                }
                $comment = $comment?$comment:$v['column_name'];
                $header[$v['column_name']] = $comment;
            }
        }
        $fields = $fields?substr($fields,1):'';
        $where1 = input('where1','');
        $result = $instance->export($where1,$fields,$order);
        if ($result) {      // 追加header
            $_temp = $result[0];
            if(count($_temp) != count($header)) {
                foreach ($_temp as $k => $v){
                    if(!isset($header[$k])){
                        $header[$k] = $k;
                    }
                }
            }
        }

        if($_table && $_table[0]['table_comment']){
            $title = $_table[0]['table_comment'];
        }
        $title = '导出'.($title ? $title.'_'.date('Ymd') : $name.'_'.date('Ymd'));
        $csv = new \ParseCsv\Csv();
        $csv->output("{$title}.csv", $result,$header);
        unset($result);
        ob_flush();
        flush();
        return $this->__s('导出成功');
    }
}
